/**
 *  created by lllwx
 *  date: 2022/1/20
 *  time: 5:31 下午
 *  version: 1.0
 *  desc: 防抖指令
 * 无配置调用方式 v-debounce="handleObjectEvent"
 * 配置参数防抖调用 v-debounce="[handleObjectEvent, wait, event]"
 */
import { getApp }  from '@/utils'

getApp().directive('debounce', {
  mounted(el, binding) {
    let fn = binding.value;
    let wait = 1000;
    let event = 'click';
    if (binding.value instanceof Array) {
      const [f, w, e] = binding.value;
      fn = f;
      wait && (wait = w);
      e && (event = e);
    }

    let timeout: NodeJS.Timeout | null = null;
    // el.lastTime 上次事件触发时间
    el.addEventListener(event, () => {
      const nowTime = new Date().getTime();
      // 没超过wait时间，重置timeout
      if (el.lastTime && nowTime - el.lastTime < wait) {
        timeout && clearTimeout(timeout);
        timeout = null;
      }
      el.lastTime = nowTime;
      timeout = setTimeout(() => {
        typeof fn === 'function' && fn();
      }, wait);
    });
  },
});
